package com.gylang.springmini.support;

import cn.hutool.core.util.ReflectUtil;

import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.function.Supplier;

/**
 * @author gylang
 * data 2021/11/17
 */
public class InvokeUtil {


    public static Object privilegedInvoke(Object instance, Method method, Object... parameters) {
        if (System.getSecurityManager() != null) {
            return AccessController.doPrivileged((PrivilegedAction<Object>) () -> ReflectUtil.invoke(instance, method, parameters));
        } else {
            return ReflectUtil.invoke(instance, method, parameters);
        }
    }

    public static Object privilegedInvoke(Object instance, String method, Object... parameters) {
        if (System.getSecurityManager() != null) {
            return AccessController.doPrivileged((PrivilegedAction<Object>) () -> ReflectUtil.invoke(instance, method, parameters));
        } else {
            return ReflectUtil.invoke(instance, method, parameters);
        }
    }

    public static Object privilegedInvoke(Supplier<?> invoke) {
        if (System.getSecurityManager() != null) {
            return AccessController.doPrivileged((PrivilegedAction<Object>) invoke::get);
        } else {
            return invoke.get();
        }
    }

}
